package com.shanghaionstar.discover.geofence;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.framework.utils.RxSubscriptions;
import com.onstar.cn.mag.GeofenceInfoEntity;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.weight.DeleteEditText;
import com.onstar.cn.weight.ProgressLayout;
import com.onstar.cn.weight.ToastView;
import com.onstar.cn.weight.more.CustomLineLayout;
import com.shanghaionstar.R;
import com.shanghaionstar.discover.geofence.iview.IGeofenceInfoView;
import com.shanghaionstar.discover.geofence.presenter.GeofenceInfoPresenter;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.pin.model.PinModel;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.weight.CommonInputLayout;
import com.shanghaionstar.weight.CommonProgressButton;

import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by 7828wc on 2016/6/29.
 */
@ContentView(R.layout.discover_geofence_info)
public class GeofenceInfoActivity extends SwipeActivity implements IGeofenceInfoView {
    @FindViewById
    private CustomLineLayout geofence_center_layout, geofence_range_layout, geofence_rule_layout;
    @FindViewById
    private CommonInputLayout et_phone_name, et_geofence_name;
    @FindViewById
    private ProgressLayout loading_progress;
    @FindViewById
    private CommonProgressButton btn_submit;

    private DeleteEditText input_fecne_name;

    private GeofenceInfoPresenter presenter;

//    private BrocastReceiveFactory geofenceVehicleLocation = new BrocastReceiveFactory();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter = new GeofenceInfoPresenter(getScheduler());
        presenter.setView(this);
        input_fecne_name = (DeleteEditText) et_geofence_name.findViewById(R.id.edit_value);
        input_fecne_name.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                presenter.onTouch();
                return false;
            }
        });
        presenter.getIntent();
        verifyResult(et_phone_name, FinalConstants.Register.SHOW_LOADING);
        presenter.getOwnerMobile();


        pinCallBack();

        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (!presenter.verifyUserPhone(et_phone_name)) {
//                    return;
//                }
//                if (!presenter.checkIsNull(et_geofence_name, R.string.input_geofence_name_empty)) {
//                    new ToastView(GeofenceInfoActivity.this).toast(R.string.input_mobile_empty);
//                    return;
//                }
                BusinessUtil.sendReportByClickType(GeofenceInfoActivity.this,FunctionNameFindId.GeoDefenceConfirmButton.getStringValue());
                commitData();
            }
        });
    }

    public void commitData() {
        if (CommonUtil.isNull(input_fecne_name.getText().toString())) {
            new ToastView(GeofenceInfoActivity.this).toast(R.string.input_geofence_name_empty);
            return;
        }
        if (CommonUtil.isNull(et_phone_name.getText().toString())) {
            new ToastView(GeofenceInfoActivity.this).toast(R.string.input_mobile_empty);
            return;
        } else if (!CommonUtil.isPhone(et_phone_name.getText().toString())) {
            new ToastView(GeofenceInfoActivity.this).toast(R.string.new_phone_error);
            return;
        }
        if (CommonUtil.isNull(geofence_center_layout.getRightText().toString())) {
            new ToastView(GeofenceInfoActivity.this).toast(R.string.geofence_submit_dialog_poi_title);
            return;
        }
        if (CommonUtil.isNull(geofence_range_layout.getRightText().toString())) {
            new ToastView(GeofenceInfoActivity.this).toast(R.string.geofence_submit_dialog_rage_title);
            return;
        }
        if (CommonUtil.isNull(geofence_rule_layout.getRightText().toString())) {
            new ToastView(GeofenceInfoActivity.this).toast(R.string.geofence_submit_dialog_rule_title);
            return;
        }
        String[] txts = {
                geofence_range_layout.getRightText().toString(),
                et_phone_name.getText().toString(),
                input_fecne_name.getText().toString(),
                geofence_rule_layout.getRightText().toString(),
                geofence_center_layout.getRightText().toString()};
        presenter.setupGeoFenceInfo(txts);
        if(!presenter.checkVehicleLocation()) {
            presenter.submit();
        }
    }


    @Override
    public BasePresenter getPresenter() {
        return presenter;
    }

    @Override
    public void verifyResult(View view, int errorResId) {
        if (view instanceof CommonInputLayout) {
            CommonInputLayout inputLayout = (CommonInputLayout) view;
            inputLayout.setEnabled(true);
            if (errorResId == FinalConstants.Register.NO_ERROR) {
                inputLayout.setCheckHintText(null);
            } else if (errorResId == FinalConstants.Register.CHECK_OK) {
                inputLayout.showLoading(false);
                inputLayout.setRightIcon(R.drawable.onstar_joinme_check_ok);
            } else if (errorResId == FinalConstants.Register.CHECK_CANCEl) {
                inputLayout.showLoading(false);
                inputLayout.setRightIcon(-1);
            } else if (errorResId == FinalConstants.Register.SHOW_LOADING) {
                inputLayout.showLoading(true);
            } else {
                inputLayout.setCheck(false);
                inputLayout.setCheckHintText(errorResId);
            }
        }
    }

    @Override
    public void setLoading(boolean isLoading) {
        loading_progress.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResponseError(OnStarException e) {
//        verifyResult(et_phone_name, FinalConstants.Register.CHECK_CANCEl);
        et_phone_name.showLoading(false);
        AlertDialogUtil.showDialogByOnstarException(onActivity(), e);
    }

    @Override
    public void onReponseSuccess(GeofenceInfoEntity object) {

    }

    @Override
    public void showMobile(String phone) {
//        verifyResult(et_phone_name, FinalConstants.Register.CHECK_CANCEl);
        et_phone_name.showLoading(false);
        if(!TextUtils.isEmpty(phone))
            et_phone_name.setText(phone);
    }

    /**
     * 设置输入的为中文字时限制输入超过8个汉字就不能输入
     */
    private TextWatcher textwatcher = new TextWatcher() {
        public void afterTextChanged(Editable s) {
            input_fecne_name.removeTextChangedListener(textwatcher);
            input_fecne_name.setText(presenter.calculationStr(s.toString(), GeofenceInfoPresenter.MAX_GEOFENCENAME_INPUT));
            input_fecne_name.setSelection(input_fecne_name.getText().toString().length());
            input_fecne_name.addTextChangedListener(textwatcher);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }
    };

    @Override
    public void displayView(GeofenceInfoEntity geoFenceInfo) {
        assert geoFenceInfo != null;
        geofence_center_layout.setRightText(geoFenceInfo.getCenterPoiName());
        geofence_range_layout.setRightText(geoFenceInfo.getRange() + presenter.getRangeUnit(geoFenceInfo));
        geofence_rule_layout.setRightText(geoFenceInfo.getRule());
        et_phone_name.setText(geoFenceInfo.getMobilePhone());
        et_geofence_name.setText(geoFenceInfo.getGeoFencingName());
    }

    @Override
    public void onActivityResultView(PoiItemInfo poiItemInfo) {
//        input_fecne_name.setText(presenter.calculationStr(poiItemInfo.getTitle(), GeofenceInfoPresenter.MAX_GEOFENCENAME_INPUT));
//        geofence_center_layout.setRightText(poiItemInfo.getSnippet());
        geofence_center_layout.setRightText(poiItemInfo.getTitle());
    }

    private Subscription mPinRx;
    /**
     * 从pin码页面返回
     */
    @Override
    public void pinCallBack() {
        mPinRx = RxBus.getDefault().toObserverable(RxConstants.VEHICLE_LOCATE, PinModel.class).filter(new Func1<PinModel, Boolean>() {
            @Override
            public Boolean call(PinModel pinModel) {
                return pinModel.isPinSuccess();
            }
        }).subscribe(new Action1<PinModel>() {
            @Override
            public void call(PinModel pinModel) {
                if (pinModel.isPinSuccess() && presenter != null) {
                    presenter.getVehicleLocation();
                }
            }
        });
        RxSubscriptions.add(mPinRx);
    }

    @Override
    public void onResultView(String snippet) {
        geofence_center_layout.setRightText(snippet);
        btn_submit.performClick();
    }

    @Override
    public Activity onActivity() {
        return this;
    }

    @OnClick({R.id.geofence_rule_layout, R.id.geofence_range_layout, R.id.geofence_center_layout, R.id.btn_submit,R.id.btn_common})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.geofence_center_layout:
                BusinessUtil.sendReportByClickType(GeofenceInfoActivity.this, FunctionNameFindId.GeoDefenceSetCenter.getStringValue());
                presenter.launchGeoCenter();
                break;
            case R.id.geofence_range_layout:
                BusinessUtil.sendReportByClickType(GeofenceInfoActivity.this, FunctionNameFindId.GeoDefenceSetRadius.getStringValue());
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                dialog.setSingleChoiceItems(R.array.geo_poi_bounds, -1, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String[] items = getResources().getStringArray(R.array.geo_poi_bounds);
                        geofence_range_layout.setRightText(items[which]);
                        presenter.rangeClick(which);
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
            case R.id.geofence_rule_layout:
                BusinessUtil.sendReportByClickType(GeofenceInfoActivity.this, FunctionNameFindId.GeoDefenceSetNotice.getStringValue());
                dialog = new AlertDialog.Builder(this);
                dialog.setSingleChoiceItems(R.array.geo_rule_bounds, -1, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String[] items = getResources().getStringArray(R.array.geo_rule_bounds);
                        geofence_rule_layout.setRightText(items[which]);
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
            case R.id.btn_submit:
            case R.id.btn_common:

                break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        presenter.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxSubscriptions.remove(mPinRx);
        presenter.finish();
        presenter =null;
    }
}
